<?php
/**
 * Plugin Name: mLink Widget
 * Plugin URI: http://code.google.com/p/mlink-widget/
 * Description: A WordPress plugin for integrating a mLink.cz links
 * Author: syntaxsugar
 * Author URI: http://syntaxsugar.cz
 * Version: 1.2
 */

class WP_Widget_Mlink extends WP_Widget {

    var $BaseUrl = 'http://www.mlink.cz/';
    var $connectionTimeout  = 10;
    
	function WP_Widget_Mlink() {
		$widget_ops = array('classname' => 'widget_mlink', 'description' => __('Konektor do mlink.cz') );
		$this->WP_Widget('mlink', __('mLink.cz'), $widget_ops);	
    }
    

	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;

		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['block_code'] = strip_tags( $new_instance['block_code'] );
		$instance['template'] = $new_instance['template'];

		return $instance;
	}
	
	function form( $instance ) {
        $instance = wp_parse_args( (array) $instance, array( 'title' => 'mLink.cz', 'block_code' => '', 'template' => '<li>%1$s</li>'));

        $title = strip_tags($instance['title']);
		$block_code = esc_attr($instance['block_code']);
		$template = format_to_edit($instance['template']);

		?>
		
		<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
		<p><label for="<?php echo $this->get_field_id('block_code'); ?>">Block: <input class="widefat" id="<?php echo $this->get_field_id('block_code'); ?>" name="<?php echo $this->get_field_name('block_code'); ?>" type="text" value="<?php echo attribute_escape($block_code); ?>" /></label></p>
		<textarea class="widefat" rows="3" cols="20" id="<?php echo $this->get_field_id('template'); ?>" name="<?php echo $this->get_field_name('template'); ?>"><?php echo $template; ?></textarea>

	<?php
	}
	
	function widget( $args, $instance ) {
		if ( isset($instance['error']) && $instance['error'] ) {
			return;
		}

		extract($args, EXTR_SKIP);

		$block = $instance['block_code'];
		if ( empty($block) ) {
			return;
		}

        $url = $this->BaseUrl . "showad.php?Url=" . urlencode(((isset($_SERVER['HTTPS'])&&($_SERVER['HTTPS']=='on'))?'https://':'http://'));
        $url .= urlencode($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); 
        $url .= "&block=" .urlencode($block);
        
        $data = $this->fetchFile($url);
        $title = $instance['title'];
		$desc = '';
		$link = '';
                
                
        $title = apply_filters('widget_title', empty($instance['title']) ? '' : $instance['title']);

        # Before the widget
		echo $before_widget;

		# The title
		if ( $title ) {
			echo $before_title . $title . $after_title;
		}
		?>
		<ul>
		<?php

		$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
        if(preg_match_all("/$regexp/siU", $data, $matches)) {
            # $matches[2] = array of link addresses
            # $matches[3] = array of link text - including HTML code
        }
  
        foreach($matches[0] as $link) {
            printf((!empty($instance['template']) ? $instance['template'] : '<li>%1$s</li>'), $link);
        }
        ?>

		
		</ul>
		<?php
	
		# After the widget
		echo $after_widget;

		unset($data);
	}
	
    function fetchFile($url)
    {
        $results='';
        if (function_exists('curl_init')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectionTimeout);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_ENCODING, 1);
            $results = curl_exec($ch);
            curl_close($ch);
        } else if (function_exists('file_get_contents')) {
            $results =  file_get_contents($url);
        } else {
            $url = parse_url($url);
            if ($handle = @fsockopen ($url["host"], 80)) {
                if (function_exists("socket_set_timeout")) {
                    socket_set_timeout($handle, $this->connectionTimeout, 0);
                } else if (function_exists("stream_set_timeout")) {
                    stream_set_timeout($handle, $this->connectionTimeout, 0);
                }
        
                fwrite($handle, "GET $url[path]?$url[query] HTTP/1.0\r\nHost: $url[host]\r\nConnection: Close\r\n\r\n");
                while (!feof($handle)) {
                    $results .= @fread($handle, 40960);
                }
                fclose($handle);
            }
        }
        return $results;
    }
}

/**
* Register Mlink Widget.
*/
function wp_widget_mlink_init() {
    register_widget('WP_Widget_Mlink');
}
add_action('widgets_init', 'wp_widget_mlink_init');

?>
